package glazedlists.chapter5;

import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.UniqueList;
import ca.odell.glazedlists.matchers.AbstractMatcherEditor;
import ca.odell.glazedlists.matchers.Matcher;
import ca.odell.glazedlists.swing.AdvancedListSelectionModel;
import ca.odell.glazedlists.swing.DefaultEventListModel;
import ca.odell.glazedlists.swing.GlazedListsSwing;
import ca.odell.issuezilla.Issue;
import glazedlists.chapter4.IssueToUserList;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class UsersSelect extends AbstractMatcherEditor<Issue> implements ListSelectionListener {
    /**
     * a list of users
     */
    private EventList<String> usersEventList;
    private EventList<String> usersSelectedList;

    /**
     * a widget for selecting users
     */
    private JList<String> usersJList;

    public UsersSelect(EventList<Issue> source) {
        EventList<String> usersNonUnique = new IssueToUserList(source);
        usersEventList = new UniqueList<>(usersNonUnique);

        DefaultEventListModel<String> usersListModel = GlazedListsSwing.eventListModelWithThreadProxyList(usersEventList);
        usersJList = new JList<>(usersListModel);

        // create an EventList containing the JList's selection
        AdvancedListSelectionModel<String> userSelectionModel = GlazedListsSwing.eventSelectionModelWithThreadProxyList(usersEventList);
        usersJList.setSelectionModel(userSelectionModel);
        usersSelectedList = userSelectionModel.getSelected();

        // handle changes to the list's selection
        usersJList.addListSelectionListener(this);
    }

    public JList<String> getJList() {
        return usersJList;
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        Matcher<Issue> newMatcher = new IssuesForUsersMatcher(usersSelectedList);
        fireChanged(newMatcher);
    }
}
